<template>
  <!-- 弹窗对话框，根据mode的不同显示不同的标题，支持新增、编辑和查看操作 -->
  <t-drawer
    :visible="dialogVisible"
    :header="mode == 'new' ? '新增' : mode == 'edit' ? '编辑' : mode == 'view' ? '查看' : ''"
    @confirm="handleSubmit"
    :confirmBtn="EDIT_FORM_SAVE_BUTTON(mode)"
    @cancel="handleClose"
    @close="handleClose"
    size="50%"
  >
    <t-form
      ref="formInstance"
      :data="pageData.formData"
      :labelWidth="120"
      :rules="pageData.formRules"
      :disabled="pageData.readOnly"
    >
      <t-form-item label="资方公司" name="funderId">
        <InputSelect v-if="!pageData.readOnly" :value="pageData.formData.funderName" @onClick="handleFunderShow" />
        <div v-else class="form__text">{{ pageData.formData.funderName }}</div>
      </t-form-item>

      <t-form-item label="国外主体" name="funderGlobalMainPartId">
        <InputSelect
          v-if="!pageData.readOnly"
          :value="pageData.formData.funderGlobalMainPartName"
          @onClick="handleMainPartShow"
        />
        <div v-else class="form__text">{{ pageData.formData.funderGlobalMainPartName }}</div>
      </t-form-item>

      <t-form-item label="备注" name="remark">
        <t-textarea v-if="!pageData.readOnly" v-model="pageData.formData.remark" />
        <div v-else class="form__text">{{ pageData.formData.remark }}</div>
      </t-form-item>
    </t-form>
  </t-drawer>

  <SelectTable
    v-if="pageData.funder.show"
    :loading="pageData.funder.loading"
    title="选择资方"
    :showDialog="pageData.funder.show"
    width="60vw"
    rowSelectionType="single"
    :tableData="pageData.funder.data.records"
    :columns="funderColumns"
    @onConfirm="handleFunderConfirm"
    @onCancel="handleFunderClose"
    :pagination="pageData.funder.pagination"
    @page-change="handleFunderPageChange"
    :filter-value="pageData.funder.filterValue"
    @filter-change="handleFunderFilterChange"
  />

  <SelectTable
    v-if="pageData.mainPart.show"
    :loading="pageData.mainPart.loading"
    title="选择国外主体"
    :showDialog="pageData.mainPart.show"
    width="60vw"
    rowSelectionType="single"
    tableMaxHeight="32vh"
    :tableData="pageData.mainPart.data.records"
    :columns="mainPartColumns"
    placement="center"
    @onConfirm="handleMainPartConfirm"
    @onCancel="handleMainPartClose"
    :pagination="pageData.mainPart.pagination"
    @page-change="handleMainPartPageChange"
  >
    <template #toolkit>
      <t-form class="crud-form" :data="pageData.mainPart.filterValue">
        <t-space direction="vertical" style="width: 100%" size="small">
          <t-row>
            <t-col :span="6">
              <t-form-item :labelWidth="120" label="中文主体名称" name="customerName">
                <t-input
                  maxlength="50"
                  v-model="pageData.mainPart.filterValue.customerName"
                  placeholder="请输入中文主体名称进行筛选"
                />
              </t-form-item>
            </t-col>
            <t-col :span="6">
              <t-form-item :labelWidth="120" label="英文主体名称" name="englishName">
                <t-input
                  maxlength="50"
                  v-model="pageData.mainPart.filterValue.englishName"
                  placeholder="请输入英文主体名称进行筛选"
                />
              </t-form-item>
            </t-col>
          </t-row>
          <t-row>
            <t-col :span="6">
              <t-form-item :labelWidth="120" label="英文昵称" name="englishNickname">
                <t-input
                  maxlength="50"
                  v-model="pageData.mainPart.filterValue.englishNickname"
                  placeholder="请输入英文主体昵称进行筛选"
                />
              </t-form-item>
            </t-col>
            <t-col :span="6">
              <t-form-item :labelWidth="120" label="所属地区" name="countryId">
                <InputSelect
                  :value="pageData.mainPart.filterValue.countryName"
                  placeholder="点击右边按钮选择国家/地区"
                  @onClick="handleRegionShow"
                />
              </t-form-item>
            </t-col>
          </t-row>

          <div class="crud-form__operations">
            <t-button theme="primary" @click="handleMainPartFilterChange">查询</t-button>
            <t-button theme="warning" @click="handleMainPartFilterReset">重置</t-button>
          </div>
        </t-space>
      </t-form>
    </template>
  </SelectTable>

  <SelectTable
    v-if="pageData.region.show"
    :loading="pageData.region.loading"
    title="选择国家/地区"
    :showDialog="pageData.region.show"
    width="60vw"
    rowSelectionType="single"
    :zIndex="2600"
    :tableData="pageData.region.data.records"
    :columns="regionColumns"
    @onConfirm="handleRegionConfirm"
    @onCancel="handleRegionClose"
    :pagination="pageData.region.pagination"
    @page-change="handleRegionPageChange"
    :filter-value="pageData.region.filterValue"
    @filter-change="handleRegionFilterChange"
  />
</template>

<script lang="tsx" setup>
// 框架和组件库
import { reactive, ref, toRaw } from "vue";
import { type FormInstanceFunctions } from "tdesign-vue-next";

// TS 类型文件
import type { ISelectTableGroups } from "@/types";

// 工具函数
import { http } from "@/utils/fetch";

// 常量
import { EDIT_FORM_SAVE_BUTTON, PAGINATION_VALUE } from "@/common/constants";

// API
import { getFunderList, getMainPartList } from "@/api/merchants";
import { getRegionList } from "@/api/region";

// 业务组件
import { tableColumns as funderColumns } from "@/pages/Dashboard/Merchants/Funder/components/columns";
import { tableColumns as mainPartColumns } from "@/pages/Dashboard/Merchants/MainPart/components/columns";
import { tableColumns as regionColumns } from "@/pages/Dashboard/Info/Region/components/columns";

const props = defineProps({
  id: {
    type: String,
    required: true
  },
  dialogVisible: {
    type: Boolean,
    default: false
  },
  mode: {
    type: String,
    required: true
  }
});

const emits = defineEmits(["close"]);

const formInstance = ref<FormInstanceFunctions | null>(null);

const GET_FORM_PATH = "/funder/relatedInfo/findOne"; // 查询接口
const CREATE_FORM_PATH = "/funder/relatedInfo/create"; // 创建接口
const UPDATE_FORM_PATH = "/funder/relatedInfo/update"; // 更新接口

const pageData = reactive({
  readOnly: false,
  formData: {
    id: "",
    createdTime: "",
    createdBy: "",
    status: 0,
    remark: "",
    updatedBy: "",
    updatedTime: "",
    createdByName: "",
    updatedByName: "",
    hasDeleted: 0,
    funderId: "",
    funderName: "",
    funderGlobalMainPartId: "",
    funderGlobalMainPartName: "",
    funder: {
      id: "",
      createdTime: "",
      createdBy: "",
      status: 0,
      remark: "",
      updatedBy: "",
      updatedTime: "",
      createdByName: "",
      updatedByName: "",
      hasDeleted: 0,
      companyName: "",
      companyShortName: "",
      address: "",
      companyEngName: "",
      companyEngShortName: "",
      engAddress: "",
      bankName: "",
      bankEngName: "",
      bankEngAddress: "",
      swiftCode: "",
      bankAccount: "",
      payeeEngName: "",
      unionPayCode: ""
    },
    funderGlobalMainPart: {
      id: "",
      createdTime: "",
      createdBy: "",
      status: 0,
      remark: "",
      updatedBy: "",
      updatedTime: "",
      createdByName: "",
      updatedByName: "",
      hasDeleted: 0,
      customerName: "",
      englishName: "",
      englishNickname: "",
      countryId: "",
      country: ""
    }
  },
  formRules: {
    funderId: [{ required: true, message: "请选择资方信息", type: "error" }],
    funderGlobalMainPartId: [{ required: true, message: "请选择国外主体", type: "error" }]
  },
  funder: {
    show: false,
    loading: false,
    data: {},
    filterValue: {},
    pagination: {
      pageSize: 20,
      total: 0,
      current: 1
    }
  } as ISelectTableGroups,
  mainPart: {
    show: false,
    loading: false,
    data: {},
    filterValue: {
      customerName: "",
      englishName: "",
      englishNickname: "",
      countryId: "",
      countryName: ""
    },
    pagination: {
      pageSize: 20,
      total: 0,
      current: 1
    }
  } as ISelectTableGroups,
  region: {
    show: false,
    loading: false,
    data: {},
    filterValue: {
      countryName: ""
    },
    pagination: {
      pageSize: 20,
      total: 0,
      current: 1
    }
  } as ISelectTableGroups
});

/**
 * 初始化表单数据。
 * 根据不同的操作模式（新增、编辑、查看），加载不同的数据。
 * @param id - ID，用于编辑和查看模式下查询信息。
 */
const initFormData = async (id = "") => {
  if (props.mode === "edit" || props.mode === "view") {
    const resultData = await http("GET", `${GET_FORM_PATH}?id=${encodeURIComponent(id)}`);
    pageData.formData = resultData.data;

    pageData.formData.funderName = pageData.formData.funder.companyName;
    pageData.formData.funderGlobalMainPartName = pageData.formData.funderGlobalMainPart.customerName;
  }
};

// 资方的选择列表方法
const getFunderData = async () => {
  pageData.funder.loading = true;
  const resultData = await getFunderList(
    pageData.funder.pagination.current,
    pageData.funder.pagination.pageSize,
    pageData.funder.filterValue
  );
  if (resultData.code === 200) {
    pageData.funder.data = resultData.data;
    pageData.funder.pagination.total = resultData.data.total;
    pageData.funder.pagination.current = resultData.data.current;
    pageData.funder.pagination.pageSize = resultData.data.size;
    pageData.funder.loading = false;
  }
};

const handleFunderConfirm = (e: Record<string, any>) => {
  pageData.formData.funderId = e.options.currentRowData.id;
  pageData.formData.funderName = e.options.currentRowData.companyName;
  handleFunderClose();
};

const handleFunderShow = () => {
  pageData.funder.show = true;
  getFunderData();
};
const handleFunderClose = () => {
  pageData.funder.show = false;
};

const handleFunderFilterChange = (filters: Record<string, any>) => {
  pageData.funder.filterValue = filters;
  pageData.funder.pagination = structuredClone(PAGINATION_VALUE);
  getFunderData();
};

const handleFunderPageChange = (pageInfo: Record<string, any>) => {
  pageData.funder.pagination.pageSize = pageInfo.pageSize;
  pageData.funder.pagination.current = pageInfo.current;
  getFunderData();
};

// 国外主体的的选择列表方法
const getMainPartData = async () => {
  pageData.funder.loading = true;
  const resultData = await getMainPartList(
    pageData.mainPart.pagination.current,
    pageData.mainPart.pagination.pageSize,
    pageData.mainPart.filterValue
  );
  if (resultData.code === 200) {
    pageData.mainPart.data = resultData.data;
    pageData.mainPart.pagination.total = resultData.data.total;
    pageData.mainPart.pagination.current = resultData.data.current;
    pageData.mainPart.pagination.pageSize = resultData.data.size;
    pageData.mainPart.loading = false;
  }
};

const handleMainPartConfirm = (e: Record<string, any>) => {
  pageData.formData.funderGlobalMainPartId = e.options.currentRowData.id;
  pageData.formData.funderGlobalMainPartName = e.options.currentRowData.customerName;
  handleMainPartClose();
};

const handleMainPartShow = () => {
  pageData.mainPart.show = true;
  getMainPartData();
};
const handleMainPartClose = () => {
  pageData.mainPart.show = false;
};

const handleMainPartFilterChange = () => {
  pageData.mainPart.pagination = structuredClone(PAGINATION_VALUE);
  getMainPartData();
};

const handleMainPartFilterReset = () => {
  pageData.mainPart.pagination = structuredClone(PAGINATION_VALUE);
  pageData.mainPart.filterValue = {
    customerName: "",
    englishName: "",
    englishNickname: "",
    countryId: "",
    countryName: ""
  };
  getMainPartData();
};

const handleMainPartPageChange = (pageInfo: Record<string, any>) => {
  pageData.mainPart.pagination.pageSize = pageInfo.pageSize;
  pageData.mainPart.pagination.current = pageInfo.current;
  getMainPartData();
};

// 选择国家地区
const getRegionData = async () => {
  pageData.region.loading = true;
  const resultData = await getRegionList(
    pageData.region.pagination.current,
    pageData.region.pagination.pageSize,
    pageData.region.filterValue
  );
  if (resultData.code === 200) {
    pageData.region.data = resultData.data;
    pageData.region.pagination.total = resultData.data.total;
    pageData.region.pagination.current = resultData.data.current;
    pageData.region.pagination.pageSize = resultData.data.size;
    pageData.region.loading = false;
  }
};

const handleRegionConfirm = (e: Record<string, any>) => {
  pageData.mainPart.filterValue.countryId = e.options.currentRowData.id;
  pageData.mainPart.filterValue.countryName = e.options.currentRowData.countryName;
  handleRegionClose();
};

const handleRegionShow = () => {
  pageData.region.show = true;
  getRegionData();
};
const handleRegionClose = () => {
  pageData.region.show = false;
};

const handleRegionFilterChange = (filters: Record<string, any>) => {
  pageData.region.filterValue = filters;
  pageData.region.pagination = structuredClone(PAGINATION_VALUE);
  getRegionData();
};

const handleRegionPageChange = (pageInfo: Record<string, any>) => {
  // console.log(pageInfo, newDataSource);
  pageData.region.pagination.pageSize = pageInfo.pageSize;
  pageData.region.pagination.current = pageInfo.current;
  getRegionData();
};

/**
 * 提交表单。
 * 根据不同的操作模式（新增、编辑），调用不同的接口保存信息。
 */
const handleSubmit = async () => {
  const validateResult = await formInstance?.value?.validate();
  if (validateResult === true) {
    let resultData;

    if (props.mode === "view") {
      handleClose();
    }

    const postFormData = structuredClone(toRaw(pageData.formData));

    if (props.mode === "new") {
      // 新增
      resultData = await http("POST", CREATE_FORM_PATH, postFormData);
    } else {
      // 更新
      // postFormData.updatedTime = new Date().toISOString();
      // postFormData.updatedBy = userStore.userData?.id;

      resultData = await http("POST", UPDATE_FORM_PATH, postFormData);
    }

    // 根据接口返回结果，提示操作成功或失败，并关闭对话框
    if (resultData.code === 200) {
      emits("close", "success");
    }
  }
};

const handleClose = () => {
  // 关闭对话框，并返回取消操作标识
  emits("close", "cancel");
};

// 如果是查看模式，设置表单为只读
if (props.mode == "view") {
  pageData.readOnly = true;
}

// 初始化表单数据，根据传入的 ID
initFormData(props.id);
</script>
